//
//  MessageVC.m
//  HuoFeiDaShipper
//
//  Created by mac on 2019/11/12.
//  Copyright © 2019 zhuchongjin. All rights reserved.
//

#import "MessageVC.h"
#import "MessageCell.h"
#import "MessageModel.h"
#import "SourcesOrderListDetailVC.h"
#import "SourcesOrderVC.h"
#import "BiddingDriverListVC.h"
#import "ShipperAuthVC.h"
@interface MessageVC ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic,strong) MessageCell *messageCell;
@property (nonatomic,strong) CJTableView *tableView;
@property (nonatomic,strong) NSMutableArray *modelArray;
@property (nonatomic,strong) NSString *refreshType; //刷新
@property (nonatomic,readwrite) int page;
@end

@implementation MessageVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self setTitleName:@"通知消息"];
    [self setBackLeftButton:@""];
    self.messageCell = [[MessageCell alloc]initWithFlex:nil reuseIdentifier:nil];
    [self.view addSubview:self.tableView];
    WS(ws);
    self.tableView.placeHolderView = [[KKTableViewNoDataView alloc] initWithFrame:self.tableView.bounds image:[UIImage imageNamed:@"no_data"] viewClick:^{
           [ws.tableView.mj_header beginRefreshing];
    }];
    [self initData];
    [self loadData];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:YES];
    [self.tableView.mj_header beginRefreshing];
}

- (void)initData{
    self.modelArray = [[NSMutableArray alloc]init];
    self.page = 1;
}

- (void)loadData{
    
    NSString *strUrl = CJStringWithFormat(@"%@/ntocc-basic-api/jpushMessage",CJBaseUrl);
    NSDictionary *dicPra = @{@"pageNum":CJStringWithFormat(@"%d",self.page),
                             @"pageSize":@"10",
    };
    WS(ws);
    [[HDNetworking sharedHDNetworking] GET:strUrl parameters:dicPra success:^(id  _Nonnull responseObject) {

        DLog(@"++++++++%@",responseObject);
        NSArray *list = responseObject[@"records"];
        NSString *total = CJStringWithFormat(@"%@",responseObject[@"total"]);
        if (list.count > 0) {

           if ([ws.refreshType isEqualToString:@"down"]) {
               [ws.modelArray removeAllObjects];
           }

           NSError * error ;
           NSArray *arr = [MessageModel arrayOfModelsFromDictionaries:list error:&error];
           [ws.modelArray addObjectsFromArray:arr];

           [ws.tableView.mj_header endRefreshing];
           [ws.tableView.mj_footer endRefreshing];

           if (ws.modelArray.count == total.intValue) {
               [ws.tableView.mj_footer endRefreshingWithNoMoreData];
           }

        }else{
//           [ws.modelArray removeAllObjects];
           [ws.tableView.mj_header endRefreshing];
           [ws.tableView.mj_footer endRefreshingWithNoMoreData];
        }
        [ws.tableView reloadData];

    } failure:^(NSError * _Nonnull error) {
        DLog(@"++++++++%@",error);
        [ws.tableView.mj_header endRefreshing];
        [ws.tableView.mj_footer endRefreshing];
    }];
    
//    NSString *filePath=[[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:@"JPushNotice.plist"];
//
//    //4.读取数据
//    self.modelArray = [NSMutableArray arrayWithContentsOfFile:filePath];
//
//    [self.modelArray reverse];

}

- (void)downRefresh{
    self.refreshType = @"down";
    self.page = 1;
    [self loadData];
}

- (void)upRefresh{
    self.refreshType = @"up";
    self.page ++;
    [self loadData];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.modelArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

        static NSString *identifier = @"MessageCell";
        MessageCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if (cell == nil) {
            cell = [[MessageCell alloc] initWithFlex:nil reuseIdentifier:identifier];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            
        }
        MessageModel *model = self.modelArray[indexPath.row];
        [cell setCellInfoWithModel:model];
        WS(ws);
        cell.blockDetail = ^(id anyObject) {
            [ws didSelectRowAtIndexPathAction:indexPath];
        };
        return cell;

}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    MessageModel *model = self.modelArray[indexPath.row];
    [self setMessagePutReadWithMessageModel:model isDetail:NO AtIndexPath:indexPath];
}

- (void)didSelectRowAtIndexPathAction:(NSIndexPath *)indexPath{
    
    //    {
    //    pushTime = "2020-10-19 14:19:41",
    //    isSystem = "0",
    //    key = "2001",
    //    name = "运单通知",
    //    type = "2001",
    //    params = "code=73be78cc182143e58eb4f3a40c96d638",
    //}
    MessageModel *model = self.modelArray[indexPath.row];
    
    [self setMessagePutReadWithMessageModel:model isDetail:YES AtIndexPath:indexPath];
    
    NSString * jsonString = model.extras;
    NSError *err;
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                    options:NSJSONReadingMutableContainers
                                                          error:&err];
    
    NSString *strCode = [CJControl getThreeUnaryValueStr:dic[@"params"]];
    if (strCode.length >=6) {
        strCode = [strCode substringFromIndex:5];
    }
    // type: 2001 运单详情， 2002 运单列表， 2003 竞价列表

    if ([[CJControl getThreeUnaryValueStr:dic[@"key"]] isEqualToString:@"2001"]) {

        SourcesOrderListDetailVC *vc = [[SourcesOrderListDetailVC alloc]init];
        vc.strCode = strCode;
        [self pushVc:vc];

    }else if ([[CJControl getThreeUnaryValueStr:dic[@"key"]] isEqualToString:@"2002"]) {

        SourcesOrderVC *vc = [[SourcesOrderVC alloc]init];
        vc.strCode = strCode;
        [self pushVc:vc];

    }else if ([[CJControl getThreeUnaryValueStr:dic[@"key"]] isEqualToString:@"2003"]) {
        BiddingDriverListVC *vc = [[BiddingDriverListVC alloc]init];
        vc.strCode = strCode;
        [self pushVc:vc];
    }else if ([[CJControl getThreeUnaryValueStr:dic[@"key"]] isEqualToString:@"3001"]) {
        ShipperAuthVC *vc = [[ShipperAuthVC alloc]init];
        [self pushVc:vc];
    }
}

- (void)setMessagePutReadWithMessageModel:(MessageModel *)model isDetail:(BOOL)isDetai AtIndexPath:(NSIndexPath *)indexPath{
    
    NSString *strURL = CJStringWithFormat(@"%@/ntocc-basic-api/jpushMessage",CJBaseUrl);
    NSDictionary *dic = @{
        @"code":model.code
    };
    WS(ws);
    [[HDNetworking sharedHDNetworking] PUT:strURL parameters:dic success:^(id  _Nonnull responseObject) {

        if (isDetai) {
            
        }else{
//            [ws.tableView.mj_header beginRefreshing];

            model.havaRead = @"1";
            [ws.tableView reloadRow:indexPath.row inSection:indexPath.section withRowAnimation:UITableViewRowAnimationFade];
        }
    } failure:^(NSError * _Nonnull error) {
    DLog(@"++++++++%@",error);

    }];
}

- (CJTableView *)tableView{
    if (!_tableView) {
        _tableView = CJTableView.tbInitFrameStyle(CGRectMake(0, kTopHeight + CJTableToTopHeight, SCREEN_WIDTH, SCREEN_HEIGHT-kTopHeight - CJTableToTopHeight),UITableViewStylePlain)
        .tbDelegate(self)
        .tbDataSource(self)
        .tbSetOther(YES)
        .tbEstimatedRowHeight(YES)
        .tbMjHeadFooter(YES)
        ;
        WS(ws);
        _tableView.blockMjHeader = ^(BOOL isheader) {

            if (isheader) {
                [ws downRefresh];
            } else {
                [ws upRefresh];
            }
        };
    }
    
    return _tableView;
}

@end
